package com.example.admin.controller;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.admin.entity.SysUser;
import com.example.shrio.conf.CustomizedToken;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import com.example.util.CurrentUser;
import com.example.util.EntityUtil;
import com.example.util.LoginType;
import com.example.util.RedisKeys;

/**
 * 
 * @author wangkai
 *
 * @date: 2019年6月4日 下午2:42:15
 */
@RestController
@RequestMapping(value = "/admin/home")
public class HomeController {

	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;

	/**
	 * 登陆
	 * 
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/login")
	public AjaxResult login(String account, String password) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (account != null && password != null) {
			CustomizedToken token = new CustomizedToken(account, password, LoginType.ADMIN.toString());
			Subject subject = CurrentUser.getSubject();
			subject.login(token);
			Map<String, Object> m = new HashMap<>();
			SysUser user = CurrentUser.getAdminUser();
			Serializable sessionId = subject.getSession().getId();
			m.put("user", (SysUser) EntityUtil.formateEntity(user));
			m.put("token", sessionId);
			result.put("data", m);
			redisTemplate.opsForValue().set(RedisKeys.getShiroSysUserTokenKey(sessionId.toString()), user.getAccount(),
					30, TimeUnit.MINUTES);
			redisTemplate.opsForValue().set(RedisKeys.getShiroSysUserKey(user.getAccount()), sessionId, 30,
					TimeUnit.MINUTES);
			return new AjaxResult(APIState.S00, "登陆成功", result);
		}
		return new AjaxResult(APIState.S01, "用户名或密码未填");
	}

	/**
	 * 登出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public AjaxResult logout() {
		SysUser sysUser = CurrentUser.getAdminUser();
		String key = RedisKeys.getShiroSysUserTokenKey(CurrentUser.getSession().getId().toString());
		String userKay = RedisKeys.getShiroSysUserKey(sysUser.getAccount());
		redisTemplate.delete(key);
		redisTemplate.delete(userKay);
		CurrentUser.logout();
		return new AjaxResult(APIState.S00, "登出成功");
	}

}
